package cn.cocho.module.common.web.tools;

import java.io.*;

/**
 * Created by shk on 14/12/11.
 */
class FileUtils {


    public static String readFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        InputStreamReader in = null;
        BufferedReader br = null;
        try {
            in = new InputStreamReader(new FileInputStream(file), "UTF-8");
            br = new BufferedReader(in);
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
            }
        }
        return sb.toString();
    }

    public static boolean writeFile(String filePath, String content) {
        boolean result = false;
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
            out.write(content);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (Exception e) {
            }
        }
        return result;
    }

    public static void deleteForder(File path) {// 删除目录及其子目录
        if (!path.exists())
            return;
        if (path.isFile()) {
            path.delete();
            System.out.println("删除目录下的文件：" + path);
            return;
        }
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            deleteForder(files[i]);
        }
        path.delete();
        System.out.println("删除目录：" + path);
    }


}
